# -*- coding=utf-8 -*-
'''
Created on Aug 7, 2016

@author: corvo
'''
from Basehandler import BaseHandler
from Database.tables import Express
from Database.tables import ExpressModify
from datetime import datetime
from Utlis.ReturnCodeConfig import CodeTable

import json
from Utlis.Helper import check_superuser

class ModifyStateHandler(BaseHandler):
    """
    工作人员更新快递状态, 通过手机号和时间戳确定
    """
    
    def post(self):
        retjson = {'code':200, 'content':''}
        
        try:
            _modify_json= self.get_argument('state_json')   # 修改信息
        except ValueError as e:
            retjson['code']    = 300
            retjson['content'] = CodeTable[300]
            self.write_back(retjson)
            return

        try:
            _modify_spec    = json.loads(_modify_json)
            _modify_user_id = _modify_spec['user_id']          # 超级用户id
            _modify_arr     = _modify_spec['content']         # json数据(要修改的内容)
        except Exception as e:
            retjson['code'] = 303
            retjson['content'] = CodeTable[303]
            self.write_back(retjson)
            return 

#         print(type(_modify_spec))
#         print(_modify_spec['content'])
        if not check_superuser(_modify_user_id):
            retjson['code'] = 305
            retjson['content'] = CodeTable[305]
            self.write_back(retjson)
            return

#         print (_modify_user_id)
#         print (_modify_arr)


#       遍历json数组, 修改数据
#       使用了较多的异常处理, 但是没有更好的办法了 
        for _modify_item in _modify_arr:
#             print (_modify_item)
            try:
                _user_phone  = _modify_item['user_phone']
                _time_stamp  = _modify_item['sub_time']
                _received    = _modify_item['received']
                _finish      = _modify_item['finish']
                _submit_time = long(_time_stamp)                # 时间戳
                _query_time  = datetime.fromtimestamp(_submit_time)
            except Exception as e:
                retjson['code']    = 303
                retjson['content'] = CodeTable[303]
                self.write_back(retjson)
                return 

#             print (type(_time_stamp))

            exist_info =  self.db.query(Express)              \
                        .filter(Express.phone == _user_phone, \
                                Express.submittime == _query_time)
                        
            try:
                exist_info.one()
                exist_info.update({"finish": _finish, "receiving": _received})
            except Exception as e:
                retjson['code'] = 500 
                retjson['content'] = CodeTable[500] # u'未找到该条记录'
                self.write_back(retjson)
                return

        # 添加记录
        modify = ExpressModify(
                    superuser = _modify_user_id,
                    modify    = _modify_json,
                    modifytime = datetime.now()
                )
        self.db.add(modify)

        try:
            self.db.commit()
            retjson['content'] = CodeTable[200]  # 修改成功
        except Exception as e:
            self.db.rollback()
            retjson['code'] = 500
            retjson['content'] = CodeTable[500]

        self.write_back(retjson)
        return


"""
        exist_info =  self.db.query(Express)                  \
                        .filter(Express.phone == _user_phone, \
                                Express.submittime == _query_time)

        try:
            exist_info.one()
            exist_info.update({"finish": 1})
        except Exception:
            retjson['code'] = 401
            retjson['content'] = u'未找到该条记录'
            self.write_back(retjson)
            return

        try:
            self.db.commit()
            retjson['content'] = u'修改状态成功'
        except Exception, e:
            self.db.rollback()
            retjson['code'] = 400
            retjson['content'] = u"数据库修改失败"

        self.write_back(retjson)
"""
